//
//  CategorySegmentViewController.m
//  Tang
//
//  Created by 352324497@qq.com on 15/12/7.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "CategorySegmentViewController.h"
#import "CategorySKUViewController.h"
#import "CategoryListsViewController.h"
#import "CategoryListsModel.h"
#import "CategorySKUModel.h"
@interface CategorySegmentViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) UISegmentedControl *segment;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, strong)NSMutableArray *SKUModelArray;
@property (nonatomic, strong)NSMutableArray *listsModelArray;
@property (nonatomic, strong)CategoryListsViewController *listsVC;
@property (nonatomic, strong)CategorySKUViewController *SKUVC;
@end

@implementation CategorySegmentViewController

{
    CGFloat segmentHeight;
}

// 添加子控制器
- (void)initChildController
{
    CGFloat height = KHeight - segmentHeight - 64;
    
    self.listsVC = [[CategoryListsViewController alloc]init];
    self.listsVC.text = self.text;
    self.listsVC.view.frame = CGRectMake(KWidth, 0, KWidth, height);
    [self.scrollView addSubview:self.listsVC.view];
    [self addChildViewController:self.listsVC];
    
    self.SKUVC = [[CategorySKUViewController alloc]init];
    self.SKUVC.text = self.text;
    self.SKUVC.view.frame = CGRectMake(0, 0, KWidth, height);
    [self.scrollView addSubview:self.SKUVC.view];
    [self addChildViewController:self.SKUVC];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.listsVC.text = self.text;
    
    self.navigationItem.title = self.text;
    segmentHeight = 38 * Kx6;
    
    // ScrollView
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, KWidth, KHeight)];
    self.scrollView.contentSize = CGSizeMake(KWidth * 2, 0);
    self.scrollView.contentOffset = CGPointMake(0, 0);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.delegate = self;
    [self.view addSubview:self.scrollView];
    
    [self initChildController];
    
    // segment
    NSArray *array = @[@"单品", @"清单"];
    self.segment = [[UISegmentedControl alloc]initWithItems:array];
    self.segment.frame = CGRectMake(0, 0, KWidth, segmentHeight);
    self.segment.momentary = NO;
    self.segment.selectedSegmentIndex = 0;
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
    self.segment.tintColor = [UIColor clearColor];
    
    [self.segment setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14], NSForegroundColorAttributeName:[UIColor orangeColor]} forState:UIControlStateSelected];
    
    [self.segment setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14], NSForegroundColorAttributeName:[UIColor grayColor]} forState:UIControlStateNormal];
    
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, segmentHeight - 7 * Kx6, KWidth / 2, 2)];
    self.bottomView.backgroundColor = [UIColor orangeColor];
    [self.segment addSubview:self.bottomView];
    [self.view addSubview:self.segment];
    
    // 自定义返回键
    // 返回的 button
    UIButton *leftBtn=[UIButton buttonWithType:(UIButtonTypeCustom)];
    leftBtn.frame = CGRectMake(0, 0, 25, 25);
    [leftBtn setImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];
    [leftBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftItem=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem=leftItem;
    
    // url 拼接
    NSString *str = [self.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet controlCharacterSet]];
    NSString *url = [NSString stringWithFormat:@"http://open3.bantangapp.com/base/search/initData?app_installtime=1449053241.284786&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&keyword=%@&os_versions=9.1&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=8",str];
    [self requestDataWithUrl:url];
    
}

#pragma mark - 数据请求
-(void)requestDataWithUrl:(NSString *)url
{
    [[NetworkState shareInstance]reachablityStatesWithDongHua:self];
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            NSLog(@"请求失败");
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            [[NetworkState shareInstance] finshYYToVc:self];
            return ;
        }
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSDictionary *dataDic = Dic[@"data"];
        self.SKUModelArray = [NSMutableArray array];
        for (NSDictionary *dic in dataDic[@"product"])
        {
            CategorySKUModel *model = [[CategorySKUModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.SKUModelArray addObject:model];
        }
        
        self.listsModelArray = [NSMutableArray array];
        for (NSDictionary *dic in dataDic[@"topic"])
        {
            CategoryListsModel *model = [[CategoryListsModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.listsModelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.SKUVC.SKUModelArray = [NSMutableArray array];
            self.listsVC.listsModelArray = [NSMutableArray array];
            if (self.SKUModelArray.count != 0)
            {
                [self.SKUVC.collectionView reloadData];
                self.SKUVC.SKUModelArray = self.SKUModelArray;
                [self.SKUVC.collectionView reloadData];
                [[NetworkState shareInstance]finshYYToVc:self];
            }
            else
            {
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20 * Kx6, 160 * Kx6, KWidth - 40 * Kx6, 200 * Kx6)];
                label.numberOfLines = 0;
                label.textAlignment = NSTextAlignmentCenter;
                label.text = @"😂😂😂, 该关键词没有搜索到单品哦, 换个关键词吧!!";
                label.font = [UIFont systemFontOfSize:22 * Kx6];
                label.textColor = [UIColor orangeColor];
                [self.SKUVC.view addSubview:label];
            }
            if (self.listsModelArray.count != 0)
            {
                [self.listsVC.collectionView reloadData];
                self.listsVC.listsModelArray = self.listsModelArray;
                [self.listsVC.collectionView reloadData];
                [[NetworkState shareInstance]finshYYToVc:self];
            }
            else
            {
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20 * Kx6, 160 * Kx6, KWidth - 40 * Kx6, 200 * Kx6)];
                label.numberOfLines = 0;
                label.textAlignment = NSTextAlignmentCenter;
                label.text = @"😂😂😂, 该关键词没有搜索到清单哦, 换个关键词吧!!";
                label.font = [UIFont systemFontOfSize:22 * Kx6];
                label.textColor = [UIColor orangeColor];
                [self.listsVC.view addSubview:label];
            }
        });
    }]resume];
}

#pragma mark - 点击 segment 跳转
- (void)segmentAction:(UISegmentedControl *)segment
{
    NSInteger i = segment.selectedSegmentIndex;
    [self.scrollView setContentOffset:CGPointMake(KWidth * i, 0) animated:YES];
    self.bottomView.frame = CGRectMake(KWidth / 2 * i, segmentHeight - 7 * Kx6, KWidth / 2, 2);
}

#pragma mark - 滑动翻页
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGPoint point = scrollView.contentOffset;
    self.segment.selectedSegmentIndex = point.x / KWidth;
    self.bottomView.frame = CGRectMake(KWidth / 2 * self.segment.selectedSegmentIndex, segmentHeight - 7 * Kx6, KWidth / 2, 2);
}
#pragma mark - 返回
-(void)backAction:(UIButton *)button
{
    [self.navigationController popToRootViewControllerAnimated:NO];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
